# -*- coding: utf-8 -*-
# 配置管理模块

import os
import json
import configparser
import logging
from pathlib import Path

class Config:
    """配置管理类"""
    
    def __init__(self, config_file=None):
        # 默认配置
        self.default_config = {
            "general": {
                "output_dir": "./output",
                "template_dir": "./templates",
                "last_used_client": "mobaxterm"
            },
            "templates": {
                "mobaxterm_url": "https://example.com/templates/mobaxterm.moba",
                "securecrt_url": "https://example.com/templates/securecrt.ini",
                "xshell_url": "https://example.com/templates/xshell.xsh"
            },
            "excel": {
                "default_sheet": "Sheet1"
            },
            "encoding": {
                "mobaxterm": "utf-8",
                "securecrt": "utf-8",
                "xshell": "utf-16"
            }
        }
        
        # 当前配置
        self.config = self.default_config.copy()
        
        # 配置文件路径
        if config_file:
            self.config_file = config_file
        else:
            # 默认使用用户目录下的配置文件
            self.config_file = os.path.join(
                str(Path.home()), 
                ".session_generator", 
                "config.json"
            )
        
        # 加载配置
        self.load()
    
    def load(self):
        """加载配置文件"""
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    user_config = json.load(f)
                    # 递归更新配置，保留默认值
                    self._update_config(self.config, user_config)
                    logging.info(f"已加载配置: {self.config_file}")
                return True
            else:
                logging.warning(f"配置文件不存在，使用默认配置: {self.config_file}")
                return False
        except Exception as e:
            logging.error(f"加载配置失败: {e}")
            # 重置为默认配置
            self.config = self.default_config.copy()
            return False
    
    def save(self):
        """保存配置到文件"""
        try:
            # 确保目录存在
            os.makedirs(os.path.dirname(self.config_file), exist_ok=True)
            
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, indent=2)
            return True
        except Exception as e:
            logging.error(f"保存配置失败: {e}")
            return False
    
    def reset(self):
        """重置为默认配置"""
        self.config = self.default_config.copy()
        return self.save()
    
    def get(self, section, key, default=None):
        """获取配置值"""
        try:
            return self.config[section][key]
        except KeyError:
            return default
    
    def set(self, section, key, value):
        """设置配置值"""
        if section not in self.config:
            self.config[section] = {}
        self.config[section][key] = value
    
    def _update_config(self, target, source):
        """递归更新配置"""
        for key, value in source.items():
            if key in target and isinstance(target[key], dict) and isinstance(value, dict):
                self._update_config(target[key], value)
            else:
                target[key] = value

class IniConfig:
    """INI格式配置管理类"""
    
    def __init__(self, config_file=None):
        self.config = configparser.ConfigParser()
        
        # 配置文件路径
        if config_file:
            self.config_file = config_file
        else:
            # 默认使用用户目录下的配置文件
            self.config_file = os.path.join(
                str(Path.home()), 
                ".session_generator", 
                "config.ini"
            )
        
        # 加载配置
        self.load()
    
    def load(self):
        """加载配置文件"""
        try:
            if os.path.exists(self.config_file):
                self.config.read(self.config_file, encoding='utf-8')
                logging.info(f"已加载配置: {self.config_file}")
                return True
            else:
                logging.warning(f"配置文件不存在: {self.config_file}")
                return False
        except Exception as e:
            logging.error(f"加载配置失败: {e}")
            return False
    
    def save(self):
        """保存配置到文件"""
        try:
            # 确保目录存在
            os.makedirs(os.path.dirname(self.config_file), exist_ok=True)
            
            with open(self.config_file, 'w', encoding='utf-8') as f:
                self.config.write(f)
            return True
        except Exception as e:
            logging.error(f"保存配置失败: {e}")
            return False
    
    def get(self, section, option, default=None, type=str):
        """获取配置值"""
        try:
            if type == str:
                return self.config.get(section, option)
            elif type == int:
                return self.config.getint(section, option)
            elif type == float:
                return self.config.getfloat(section, option)
            elif type == bool:
                return self.config.getboolean(section, option)
        except (configparser.NoSectionError, configparser.NoOptionError):
            return default
    
    def set(self, section, option, value):
        """设置配置值"""
        if not self.config.has_section(section):
            self.config.add_section(section)
        self.config.set(section, option, str(value))

def get_config(ini_format=False, config_file=None):
    """获取配置实例"""
    if ini_format:
        return IniConfig(config_file)
    return Config(config_file) 